﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Data.Common;
using System.Data.EntityClient;

namespace EFMassOperations
{
	class EFDbProviderFactoryUtils
	{
		// The following leaks a DbCommandBuilder (which is IDisposable) per each
		// .NET data provider used. But saves 30% CPU time
		static Cache<ObjectContext, string, DbCommandBuilder> commandBuilderCache =
			new Cache<ObjectContext, string, DbCommandBuilder>(
				(context) => EFConnectionStringParser.GetConnectionStringParserCache(context).Provider,
				(context, provider) => GetSqlCommandBuilder(provider));

		public static DbCommandBuilder GetSqlCommandBuilderCache(ObjectContext context)
		{
			return commandBuilderCache[context];
		}

		static DbCommandBuilder GetSqlCommandBuilder(string provider)
		{
			DbProviderFactory providerFactory = DbProviderFactories.GetFactory(provider);
			return providerFactory.CreateCommandBuilder();
		}

		public static DbCommand CreateCommand(ObjectContext context)
		{
			DbConnection dbConn = GetDbConnection(context);
			return dbConn.CreateCommand();
		}

		public static DbConnection GetDbConnection(ObjectContext context)
		{
			return ((EntityConnection)context.Connection).StoreConnection;
		}
	}
}
